
use strict;
use warnings;
use open qw(:std :utf8);

my %table;

{
	my $dfu = `kpsewhich utf8enc.dfu`;
	die 'Could not find utf8enc.dfu' unless ($? == 0);
	open IN, $dfu or die "Could not open $dfu: $!";
	while (<IN>) {
		if (/\\DeclareUnicodeCharacter{([[:xdigit:]]+)}{([^}]+)}/) {
			my $key = $1;
			my $val = $2;
			$val =~ s/\@tabacckludge//g;
			if($val =~ /(\s|~|\\[A-Za-z]+$)/) {
				$val = "\{$val\}";
			}
			$table{hex($key)} = $val;
		}
	}
	close IN;
}

sub lookup {
	my $chr = shift;
	if(my $esc = $table{ord($chr)}) {
		return $esc;
	} else {
		warn "Could not find encoding for non-ASCII character $chr";
		return $chr;
	}
}

while(<>) {
	s/([^\0-~])/lookup($1)/ge;
	print;
}

